package com.atguitu.campus.renwendemo.Controller;


import com.atguitu.campus.renwendemo.dto.AuthRequest;
import com.atguitu.campus.renwendemo.dto.AuthResponse;
import com.atguitu.campus.renwendemo.utils.AjaxResult;
import com.atguitu.campus.renwendemo.utils.JwtUtils;
import com.atguitu.campus.renwendemo.utils.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public AjaxResult authenticateUser(@RequestBody AuthRequest loginRequest) throws Exception {
        //由于jsencrypt 每次加密的密文不一样，先解密密码 得到明文
        String password = RsaUtils.decrypt(loginRequest.getPassword());
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        password
                )
        );

        String jwt = jwtUtils.generateToken(authentication.getName());
        return  AjaxResult.success(new AuthResponse(jwt));
    }

    @PostMapping("/register")
    public AjaxResult register(@RequestBody AuthRequest loginRequest) {
        // 构建用户实体
        var user = User.builder()
                .username(loginRequest.getUsername())
                .password(passwordEncoder.encode(loginRequest.getPassword())) // 密码加密
                .build();
        // 保存用户到数据库
        log.info("用户注册信息：{}",user.toString());
        log.info("密码：{}",user.getPassword());
        // 为用户生成JWT令牌
        String jwt = jwtUtils.generateToken(loginRequest.getUsername());
        return AjaxResult.success(new AuthResponse(jwt));
    }

}



